package com.yx.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.yx.config.AlipayConfig;
import com.yx.constatns.RabbitMQConstatns;
import com.yx.feign.api.OrderService;
import com.yx.vo.Order;
import com.yx.vo.OrderDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Classname AliController
 * @Date 2021/07/23 15:48
 * @Author by yx
 * @Description TODO:
 */
@Controller
@RequestMapping("/ali")
@Slf4j
public class AliController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/pay")
    @ResponseBody
    public void pay(String oid, HttpServletResponse httpResponse) throws AlipayApiException {
        log.debug("oid: {}", oid);

        // 通过oid获取订单详情
        Order order = orderService.getOrderByOid(oid);
        List<OrderDetail> orderDetails = orderService.getOrderDetailListByOid(oid);
        // 获取list集中第一个对象
        OrderDetail orderDetail = orderDetails.stream().findFirst().orElse(null);

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = oid;
        //付款金额，必填
        Double total_amount = order.getTotalPrice().doubleValue();
        //订单名称，必填
        String subject = orderDetail.getGname();
        //商品描述，可空
        String body = orderDetail.getGdesc();
        // 设置支付包超时时间,1分钟
        String timeout_express = "1m";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        Map<String,Object> dleMap = new HashMap<>();
        dleMap.put("order", order);
        dleMap.put("orderDetailList",orderDetails);
        String json = JSON.toJSONString(dleMap);
        log.debug("dleMap{}",json);
        rabbitTemplate.convertAndSend(RabbitMQConstatns.ORDER_EXCHANGE, "shop.order.pay",json);
        rabbitTemplate.convertAndSend(RabbitMQConstatns.STOCK_EXCHANGE, "shop.stock.pay",json);

        //输出
        log.debug("result:{}", result);
        try {
            httpResponse.setContentType("text/html;charset=" + AlipayConfig.charset);
            httpResponse.getWriter().write(result); //直接将完整的表单html输出到页面
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 支付宝是使用POST请求来调用这个解接口
    @PostMapping("/updateOrder")
    @ResponseBody
    public void updateOrder(HttpServletRequest request) {
        log.debug("支付包异步通知-------");

        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = requestParams.entrySet();
        for (Map.Entry<String, String[]> entry : entries) {
            String key = entry.getKey();
            String[] value = entry.getValue();
            // 将反馈的参数封装进map
            params.put(key, value[0]);
        }

        //乱码解决，这段代码在出现乱码时使用
           /* valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);*/

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            log.error("延签失败出现异常了", params);
        }

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (signVerified) {
            log.debug("支付宝验签成功");
            // 再次判断订单的id，订单的金额是否一致，支付的状态
            String trade_status = params.get("trade_status");// 获取支付的状态

            // 判断订单额状态是否是支付成功
            if ("TRADE_SUCCESS".equals(trade_status)) {

                // 获取订单的编号
                String out_trade_no = params.get("out_trade_no");

                // 修改的订单的状态
                orderService.updateOrderStatus(out_trade_no,2);
            }
        } else {
            log.debug("验签失败");
        }
    }

}
